-- Server Side

function ToggleMenu(ply)
ply:ConCommand("tdm_menu")
end
hook.Add("ShowTeam", "MyHook", ToggleMenu)


function ResetListing( ply )
	for k,v in pairs(player.GetAll()) do
		umsg.Start("apple_tdm_updatelist", v)
		umsg.End()
	end
end
--hook.Add( "PlayerInitialSpawn", "ResetListing", ResetListing )
hook.Add( "PlayerDisconnected", "ResetListing", ResetListing )


function GM:ShowHelp( ply ) -- This hook is called everytime F1 is pressed.
    umsg.Start( "MyMenu", ply ) -- Sending a message to the client.
    umsg.End()
end --Ends function



if (not file.IsDir("TDM/Friendly","DATA")) then
    file.CreateDir("TDM/Friendly")
end
if not(file.Exists("TDM/Friendly/Friendly.txt","DATA")) then
	file.Write("TDM/Friendly/Friendly.txt", 0)
	--print("[TDM] Wrote file : TDM/Friendly/Friendly.txt")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-Friendly",Color(255,255,255),"] Wrote file: TDM/Friendly/Friendly.txt\n")
end


-- Creates the Database
if sql.TableExists("apple_tdm_map") then
--MsgN("[TDM-Maps] Database 'apple_tdm_map' Already Exists!")
MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-MapsDB",Color(255,255,255),"] Database 'apple_tdm_map' Already Exists!\n")
	else
		if (!sql.TableExists("apple_tdm_map")) then
			local Query = "CREATE TABLE apple_tdm_map ( ID int, Name varchar(255) )"
			local Result = sql.Query(Query)
			if (sql.TableExists("apple_tdm_map")) then
				--MsgN("[TDM-Maps] Successfully Created Database 'apple_tdm_map'!")
				MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-MapsDB",Color(255,255,255),"] Successfully Created Database 'apple_tdm_map'!\n")
			else
				--MsgN("[TDM-Maps] Database 'apple_tdm_map' Was Not Created!")
				MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-MapsDB",Color(255,255,255),"] Database 'apple_tdm_map' Was Not Created!\n")
				MsgN( sql.LastError( Result ) )
			end	
		end
end


function TDMFriendlyFire(len, ply)
if !ply:IsSuperAdmin() then 
		umsg.Start("apple_tdm_notadmin", ply) -- Sends the message to player
		umsg.End()
return end
local TDMFF = math.Round(net.ReadString( ))
MsgN(tonumber(TDMFF))
MsgN(tonumber(file.Read("TDM/Friendly/Friendly.txt")))
if tonumber(file.Read("TDM/Friendly/Friendly.txt")) == tonumber(TDMFF) then return end
file.Write("TDM/Friendly/Friendly.txt", TDMFF)
	for k,v in pairs(player.GetAll()) do 
		umsg.Start("apple_tdm_setff", v) -- Sends the message to player
			umsg.Short(file.Read("TDM/Friendly/Friendly.txt"))
		umsg.End()
	end
end
net.Receive("TDMFriendlyFire", TDMFriendlyFire)


-- Adds Maps to the Database
function TDMListMap(len, ply)
if !ply:IsSuperAdmin() then return end

local MapName = net.ReadString( )

local LastMapIDCreated = tonumber(sql.QueryValue( "SELECT ID FROM apple_tdm_map ORDER BY ID DESC LIMIT 1" ))
if LastMapIDCreated == nil then
	LastMapIDCreated = 0
end

local LastMapIDCreated = (LastMapIDCreated + 1)
	--MsgN("[TDM-Maps] Map Was Created Successfully, MapID: "..LastMapIDCreated)
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-MapsAdd",Color(255,255,255),"] Map Was Created Successfully, MapID: ",Color(0,255,0),""..LastMapIDCreated.."\n")
	sql.Query( "INSERT INTO apple_tdm_map (`ID`, `Name`) VALUES ('"..tonumber(LastMapIDCreated).."', '"..MapName.."' ) ")
AutoFixMapID()
end
net.Receive("TDMTDMListMap", TDMListMap)


-- Deletes Maps on the Database
function TDMDeleteMap(len, ply)
if !ply:IsSuperAdmin() then return end
args = net.ReadString( )
if tonumber(args) == nil then return end

local GetMapName = sql.QueryValue( "SELECT Name FROM apple_tdm_map WHERE ID = "..args.."" ) -- Will check to see if team even exists
if GetMapName == nil then 
	MsgN("[TDM-MapDelete] Map Does Not Exist!")
return end

local GetDeleteInfo9 = sql.Query( "DELETE FROM apple_tdm_map WHERE ID = "..args.."" ) -- Attempted to delete the team
if !GetDeleteInfo9 then -- If team is deleted correctly, then it will run this fuctions
	--MsgN("[TDM-MapDelete] "..GetMapName.." Has Been Successfully Deleted!")
	MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-MapDelete",Color(255,255,255),"] ",Color(0,255,0),""..GetMapName.."",Color(255,255,255)," Has Been Successfully Deleted!\n")
	AutoFixMapID()
return end
end
net.Receive("TDMDeleteMap", TDMDeleteMap)


-- Auto Fix Maps Index
if sql.TableExists("apple_tdm_map") then
	function AutoFixMapID()
		local GetAutoFixIDM = sql.Query( "SELECT * FROM apple_tdm_map" )
		if !GetAutoFixIDM then 
		CustomMapsList2 = {}
		CustomMapsList3 = {}
		
		net.Start( "TDMTDMListMap2" )
			net.WriteTable(CustomMapsList2)
		net.Broadcast()
		
		umsg.Start("apple_tdm_updatemap")
		umsg.End()
		return end
		CustomMapsList2 = {}
		CustomMapsList3 = {}
			for k, v in pairs( GetAutoFixIDM ) do -- This will automatically update the index IDs for teams in the database
				sql.Query( "UPDATE apple_tdm_map SET ID = "..k.." WHERE ID = "..v['ID'].."" )
			--MsgN("[TDM-AutoFixMaps] Map: "..v['Name'].."("..k..") have been repaired!")
			MsgC(Color(255,255,255),"[",Color(255,0,0),"TDM-AutoFixMapsIndex",Color(255,255,255),"] Map: ",Color(0,255,0),""..v['Name'].."",Color(255,255,255),"(",Color(0,0,255),""..k.."",Color(255,255,255),") have been repaired!\n")
				CustomMapsList2[k] = {
					Name2 = tostring(v['Name'])
				}
				CustomMapsList3[k] = tostring(v['Name'])
			end
		net.Start( "TDMTDMListMap2" )
			net.WriteTable(CustomMapsList2)
		net.Broadcast()
		
		umsg.Start("apple_tdm_updatemap")
		umsg.End()
	end
AutoFixMapID()
end




-- Thank you ULX 
/*
do
GetMapList = {}
local GetMaps = file.Find( "maps/*.bsp", "GAME" )

for _, map in ipairs( GetMaps ) do
	table.insert( GetMapList, map:sub( 1, -5 ):lower() ) -- Take off the .bsp
end
table.sort( GetMapList ) -- Make sure it's alphabetical
timer.Simple(2, function()
	net.Start( "apple_tdm_customemaps" )
		net.WriteTable(GetMapList)
	net.Broadcast()
end)
PrintTable(GetMapList)
end
*/